/*===============================================
*   文件名称：server.c
*   创 建 者：     
*   创建日期：2023年04月17日
*   描    述：
================================================*/
#include <stdio.h>
#include <netinet/in.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <sqlite3.h>
#include <string.h>
int j=0;
char N;
char *str(char *p);
int sqil_func(char *p);
int myfunc(void *p,int argc,char**argv,char**argvv)
{
	int i;
	*(int*)p=0;
	for(i=0;i<argc;i++)
	{
		printf("%s=%s\n",argvv[i],argv[i]? argv[i]:"NULL");
	}

	N=*argv[0];
	return 0;
}
int main(int argc, char *argv[])
{ 
    int fd=0;
    fd=socket(AF_INET,SOCK_DGRAM,0);
    if(fd<0){
        perror("socket");
    }
    struct sockaddr_in dst;
    dst.sin_family=AF_INET;
    dst.sin_port=htons(8201);
    dst.sin_addr.s_addr=INADDR_ANY;
    int ret=0;
    ret=bind(fd,(struct sockaddr*)&dst,sizeof(dst));
    if(ret<0){
        perror("bind");
    }
    while(1){
		int t=4e8;
		for(int i=t;i>0;i--);
        char data[1024]={0};
        struct sockaddr_in send;
        int send_len=sizeof(dst);
        ret= recvfrom(fd,data,sizeof(data),0,(struct sockaddr *)&dst,&send_len);
        if(ret<0){
           perror("recvfrom");
       }
		int rc=strlen(data);
		if(rc!=20){
			continue;
		}
        str(data);
		printf("%s\n",data);
		sqil_func(data);
		ret=sendto(fd,&N,1,0,(struct sockaddr *)&dst,send_len);
		if(ret<0){
			perror("sendto");
		}
    }
    close(fd);
    return 0;
} 
char *str(char *p)
{	
    char *q=p,*t=p;
    int i=0;
    while(*q)
    {
        if((*q<=57)&&(*q>=48))
        {
            *(t+i)=*q;
            i++;
            if(i==2){
                *(t+i)=' ';
                i++;
            }
        }
        q++;
    }
    *(t+i)='\0';
    	return p;
}
int sqil_func(char *p)
{	
	char *q=p;
	sqlite3 *db;
	char *errmsg=0;
	int empty=1;
	int ret=sqlite3_open("/var/www/xuedao",&db);
	if(ret<0){
		perror("open");
	}
	ret=sqlite3_exec(db,"delete from w_m;",NULL,&empty,&errmsg);
	if(ret!=SQLITE_OK){
		printf("delete error\n");
	}
	char *t1,*t2;
	char buff[1024]={0};
	t1=strtok(q," ");
	t2=strtok(NULL," ");
	sprintf(buff,"insert into w_m values(%d,%s,%s);",j,t1,t2);
	j++;
	printf("%s\n",buff);
	ret=sqlite3_exec(db,buff,NULL,&empty,&errmsg);
	if(ret!=SQLITE_OK){
		printf("sqlite3_exec:%s\n",errmsg);
	}
	ret=sqlite3_exec(db,"select *from LED;",myfunc,&empty,&errmsg);
	if(ret!=SQLITE_OK){
		printf("select error\n");
	}
	sqlite3_close(db);
	return 0;
}
